/*
 * author      : 吴中勤
 * date        : 2019/3/12
 * description : TODO
 */

package org.wzq.learn.infrastructure.framework;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import org.wzq.learn.HttpResponseAssembler;
import org.wzq.learn.HttpResponsePayload;
import org.wzq.learn.infrastructure.lib.trace.EnableErrorReport;

@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    private static final int SYSTEM_ERROR_CODE = 500;

    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseEntity<?> handler(RuntimeException ex) {
        if (logger.isDebugEnabled()) logger.debug("GlobalExceptionHandler::handler");

        HttpResponsePayload payload = HttpResponseAssembler.unhappy(SYSTEM_ERROR_CODE, ex.getMessage());
        return new ResponseEntity<>(payload, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(value = IllegalArgumentException.class)
    @ResponseBody
    @EnableErrorReport(HttpStatus.NOT_FOUND)
    public ResponseEntity<?> handlerThrowable(Throwable ex) {
        if (logger.isDebugEnabled()) logger.debug("GlobalExceptionHandler::handlerThrowable");
        HttpResponsePayload payload = HttpResponseAssembler.unhappy(404, ex.getMessage());
        return new ResponseEntity<>(payload, HttpStatus.NOT_FOUND);
    }

//    @ExceptionHandler(value = ResponseStatusException.class)
//    public void responseExceptionHandler(HttpServletResponse response, HttpServletRequest request, ResponseStatusException ex) throws IOException {
//        int code = ex.getStatus().value();
//        System.out.println("handleIllegalArgumentException, ex.code" + code);
//
//        // 有价值的尝试
//        // 此时 设置 sampler.always 无效，估计是时机已经晚了
//        if (code > HttpStatus.BAD_REQUEST.value()) {
//            System.out.println("should collect this span");
//            tracer.withSampler(Sampler.ALWAYS_SAMPLE);
//        }
//    }
//
//    @ExceptionHandler(value = Exception.class)
//    public void allOtherExceptionHandler(HttpServletResponse response, HttpServletRequest request) throws IOException {
//        System.out.println("allOtherExceptionHandler");
//        tracer.withSampler(Sampler.ALWAYS_SAMPLE);
//    }
}

